package stardust.core.network.protocol.proxy.http;


import stardust.core.network.NetworkSession;
import stardust.core.network.ProtocolType;


public class HttpProxy
{

  private Thread listenThread;

  private NetworkSession listener;

  private String address;

  private int port;

  public HttpProxy()
  {
    this(8080);
  }

  public HttpProxy(int port)
  {
    this(null, port);
  }

  public HttpProxy(String address, int port)
  {
    this.address = address;
    this.port = port;
  }

  public void start() throws InterruptedException
  {
    this.stop();

    this.listener = NetworkSession.getInstance(ProtocolType.tcp);
    this.listener.listen(this.address, this.port);
    this.listenThread = new Thread(
    new Runnable()
    {

      public void run()
      {
        try
        {
          while (true)
          {
            NetworkSession acceptSession = listener.accept(0);
            Thread processor = new HttpProxyProcessor(acceptSession);

            processor.setDaemon(true);
            processor.start();
          }
        }
        finally
        {
          listener.disconnect();
        }
      }

    });

    this.listenThread.start();
  }

  public void stop() throws InterruptedException
  {
    if (this.listenThread != null)
    {
      this.listenThread.interrupt();
      this.listenThread.join();
    }
  }

}
